<template>
  <div>
    <!-- S头部 -->
    <!-- 头部导航 -->
    <van-nav-bar title="登录" class="navBar" left-arrow />
    <!-- 手机号/验证码表单 -->
    <van-form @submit="onSubmit" class="form" ref="form">
      <!-- 表单中的输入框组件 -->
      <!-- 1.input没有name不能进行提交数据 -->
      <!-- 2.form表单当中，button可以触发submit事件-->
      <van-field
        v-model="mobile"
        name="mobile"
        placeholder="请输入手机号码"
        :rules="formRules.mobileRules"
      >
        <template #label>
          <span class="toutiao toutiao-shouji"></span>
        </template>
      </van-field>
      <van-field
        v-model="code"
        name="code"
        placeholder="请输入验证码"
        :rules="formRules.codeRuless"
      >
        <template #label>
          <span class="toutiao toutiao-yanzhengma"></span>
        </template>
        <template #button>
          <!-- 获取验证码按钮 -->
          <!-- native-type="button" 阻止验证码按钮触发表单提交事件 -->
          <van-button
            v-if="isShowCodeBtn"
            type="default"
            round
            size="small"
            class="code-btn"
            @click="getCode"
            native-type="button"
            >获取验证码</van-button
          >
          <!-- 倒计时 -->
          <van-count-down
            v-else
            :time="60 * 1000"
            format="ss秒"
            @finish="isShowCodeBtn = true"
          />
        </template>
      </van-field>
      <!-- 登录 -->
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
    <!--E头部 -->
  </div>
</template>

<script>
import { loginAPI, getCodeAPI } from "@/api";
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      mobile: "",
      code: "",
      isShowCodeBtn: true,
      formRules: {
        mobileRules: [
          { required: true, message: "请填写用户名", trigger: "onBlur" },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "输入的号码不合法",
            trigger: "onBlur",
          },
        ],
        codeRules: [
          { required: true, message: "请填写验证码", trigger: "onBlur" },
          {
            pattern: /^[0-9]{6}$/,
            message: "请输入六位数字的验证码",
          },
        ],
      },
    };
  },
  methods: {
    ...mapMutations(["SET_TOKEN"]),
    async onSubmit() {
      const { mobile, code } = this;
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
      });

      try {
        const { data: res } = await loginAPI(mobile, code);
        this.SET_TOKEN(res.data);
        this.$router.push("/profile");
        this.$toast.success({
          message: "登录成功",
        });
        console.log(res);
      } catch (error) {
        // 区分是axios还是js导致的错误
        // axios封装的是错误对象
        // -对象 response.data存储这后端返回的数据
        // -对象 response.status 后端返回的状态码
        // error.response && error.response.status === 400
        // ？可选链操作符
        if (error.response?.status === 400) {
          // axios导致的错误
          this.$toast.fail(error.response.data.message);
        } else {
          // js导致的错误或者是status为507
          throw error;
        }
      }
    },
    // 1.验证手机号码合不合格
    // 注意点：需要通过ref获取属性,绑定name属性
    async getCode() {
      await this.$refs.form.validate("mobile");
      // 2.显示倒计时
      this.isShowCodeBtn = false;
      // 3.显示loading
      this.$toast.loading({
        message: "发送验证码中...",
        forbidClick: true,
      });
      // 4.手机号码验证合格，发送验证码请求
      try {
        await getCodeAPI(this.mobile);
        this.$toast.success("验证码发送成功！");
      } catch (error) {
        if (error.response?.status === 429) {
          // 频繁的发送验证码
          this.$toast.fail(error.response.data.message);
        } else {
          throw error;
        }
      }
    },
  },
};
</script>

<style scoped lang="less">
.navBar {
  background-color: #3296fa;
  :deep(.van-nav-bar__title) {
    color: #fff;
  }
}
:deep(.form) {
  .toutiao {
    font-size: 40px;
  }
  .van-field__label {
    flex: 1;
  }
  .van-field__value {
    flex: 20;
  }
}
.van-button {
  background-color: #3296fa;
}
.code-btn {
  background-color: #eeeeee;
  color: #9a8b7e;
  height: 0.64rem;
}
</style>